package patrol.mobile.com.mobilepatrol.utils;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Compress {
	private static final int BUFFER_LENGTH = 5000;
	/***压缩字节最小长度，小于这个长度的字节数组不适合压缩，压缩完会更大****/
	private static final int BYTE_MIN_LENGTH =50;
	
	/***字节数据是否压缩标志****/
	public static final byte FLAG_GBK_STRING_UNCOMPRESSED_BYTEARRAY = 0;
	public static final byte FLAG_GBK_STRING_COMPRESSED_BYTEARRAY = 1;
	public static final byte FLAG_UTF8_STRING_COMPRESSED_BYTEARRAY = 2;
    public static final byte FLAG_NO_UPDATE_INFO = 3;
    /**
     * 数据压缩
     * @param in
     * @param os
     */
    public static void compress(InputStream in ,OutputStream os) throws Exception{
    	
    	GZIPOutputStream gos=new GZIPOutputStream(os);
    	int count;
    	byte data[]=new byte[BUFFER_LENGTH];
    	System.out.println("********************压缩数据开始************************");
    	while((count=in.read(data,0,BUFFER_LENGTH))!=-1){
    		gos.write(data, 0, count);
    	}
    	gos.finish();
    	gos.flush();
    	gos.close();
    	System.out.println("********************压缩数据结束************************");
    }
    /***
     * 数据解压缩
     * @param in
     * @param os
     * @throws Exception
     */
    public static void decompress(InputStream in ,OutputStream os) throws IOException {
    	GZIPInputStream gis=new GZIPInputStream(in);
    	int count;
    	byte data[]=new byte[BUFFER_LENGTH];
    	System.out.println("********************解压数据开始************************");
    	while((count=gis.read(data, 0, BUFFER_LENGTH))!=-1){
    		os.write(data, 0, count);
    	}
    	gis.close();
    	System.out.println("********************解压数据结束************************");
    }
    /**
     * 字符串数据压缩
     * @param str
     * @throws Exception
     */
    public static byte[]  compressString(String str)throws Exception{
    	byte buf[]=str.getBytes();
    	ByteArrayInputStream in=new ByteArrayInputStream(buf);
    	ByteArrayOutputStream os=new ByteArrayOutputStream();
    	compress(in, os);
    	byte data[]=os.toByteArray();
    	in.close();
    	os.flush();
    	os.close();
    	return data;
    }
    /***
     * 解压数据返回字符串
     * @param buf
     * @return
     * @throws Exception
     */
    public static String decompressByteArray(byte[] buf) throws IOException {
    	ByteArrayInputStream in=new ByteArrayInputStream(buf);
    	ByteArrayOutputStream os=new ByteArrayOutputStream();
    	decompress(in,os);
    	return os.toString();
    }
    
}
